package com.cloud.spring.gson;

import com.cloud.spring.bean.BeanStore;
import com.cloud.spring.demo.entity.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import lombok.extern.log4j.Log4j2;

import java.util.*;

@Log4j2
public class GsonDemo {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().create();
        /**
         * 对象转json
         */
        User user = BeanStore.createUser();
        String userStr1 = gson.toJson(user);
        log.info(userStr1);
        /**
         * json转对象
         */
        User user2 = gson.fromJson(userStr1, User.class);
        log.info(user2);
        /**
         * 超复杂对象和json的互相转换
         */
        List<User> list = Arrays.asList(user, user2);
        Map<String, User> map1 = new HashMap<>();
        map1.put("user", user);
        map1.put("user2", user2);
        Map<String, User> map2 = new HashMap<>();
        map2.put("user1", user);
        map2.put("user2", user2);
        List<Map<String, User>> list1 = Arrays.asList(map1, map2);
        String json = gson.toJson(list1);
        List<Map<String, User>> list2 = gson.fromJson(json, new TypeToken<List<Map<String, User>>>() {
        }.getType());
        log.info(json);
        log.info(list2);
    }
}
